package com.hl.services.system.user.controller;

import cn.hutool.core.collection.CollUtil;
import com.hl.framework.auth.service.SecurityFrameworkUtils;
import com.hl.framework.core.common.enums.CommonStatusEnum;
import com.hl.framework.core.common.pojo.CommonResult;
import com.hl.framework.core.common.pojo.PageResult;
import com.hl.framework.core.common.util.object.BeanUtils;
import com.hl.services.system.dept.domain.DeptDO;
import com.hl.services.system.dept.domain.PostDO;
import com.hl.services.system.dept.service.DeptService;
import com.hl.services.system.dept.service.PostService;
import com.hl.services.system.user.domain.AdminUserDO;
import com.hl.services.system.user.domain.vo.user.*;
import com.hl.services.system.user.service.AdminUserService;
import com.hl.services.system.user.utils.UserConvert;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

import static com.hl.framework.core.common.pojo.CommonResult.success;
import static com.hl.framework.core.common.util.collection.CollectionUtils.convertList;


@Tag(name = "管理后台 - 用户")
@RestController
@RequestMapping("/system/user")
@Validated
public class UserController {

    @Resource
    private AdminUserService userService;
    @Resource
    private DeptService deptService;
    @Resource
    private PostService postService;

    @PostMapping("/create")
    @Operation(summary = "新增用户")
    @PreAuthorize("@ss.hasPermission('system:user:create')")
    public CommonResult<Long> createUser(@Valid @RequestBody UserSaveReqVO reqVO) {
        Long id = userService.createUser(reqVO);
        return success(id);
    }

    @PutMapping("update")
    @Operation(summary = "修改用户")
    @PreAuthorize("@ss.hasPermission('system:user:update')")
    public CommonResult<Boolean> updateUser(@Valid @RequestBody UserSaveReqVO reqVO) {
        userService.updateUser(reqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除用户")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('system:user:delete')")
    public CommonResult<Boolean> deleteUser(@RequestParam("id") Long id) {
        userService.deleteUser(id);
        return success(true);
    }

    @DeleteMapping("/delete-list")
    @Parameter(name = "ids", description = "编号列表", required = true)
    @Operation(summary = "批量删除用户")
    @PreAuthorize("@ss.hasPermission('system:user:delete')")
    public CommonResult<Boolean> deleteUserList(@RequestParam("ids") List<Long> ids) {
        userService.deleteUserList(ids);
        return success(true);
    }

    @PutMapping("/update-password")
    @Operation(summary = "重置用户密码")
    @PreAuthorize("@ss.hasPermission('system:user:update-password')")
    public CommonResult<Boolean> updateUserPassword(@Valid @RequestBody UserUpdatePasswordReqVO reqVO) {
        userService.updateUserPassword(reqVO.getId(), reqVO.getPassword());
        return success(true);
    }

    @PutMapping("/update-status")
    @Operation(summary = "修改用户状态")
    @PreAuthorize("@ss.hasPermission('system:user:update')")
    public CommonResult<Boolean> updateUserStatus(@Valid @RequestBody UserUpdateStatusReqVO reqVO) {
        userService.updateUserStatus(reqVO.getId(), reqVO.getStatus());
        return success(true);
    }

    @GetMapping("/page")
    @Operation(summary = "获得用户分页列表")
    @PreAuthorize("@ss.hasPermission('system:user:query')")
    public CommonResult<PageResult<UserRespVO>> getUserPage(@Valid UserPageReqVO pageReqVO) {
        // 获得用户分页列表
        PageResult<AdminUserDO> pageResult = userService.getUserPage(pageReqVO);
        if (CollUtil.isEmpty(pageResult.getList())) {
            return success(new PageResult<>(pageResult.getTotal()));
        }
        // 拼接数据
        Map<Long, DeptDO> deptMap = deptService.getDeptMap(
                convertList(pageResult.getList(), AdminUserDO::getDeptId));
        return success(new PageResult<>(UserConvert.convertList(pageResult.getList(), deptMap),
                pageResult.getTotal()));
    }

    @GetMapping({"/list-all-simple", "/simple-list"})
    @Operation(summary = "获取用户精简信息列表", description = "只包含被开启的用户，主要用于前端的下拉选项")
    public CommonResult<List<UserSimpleRespVO>> getSimpleUserList() {
        List<AdminUserDO> list = userService.getUserListByStatus(CommonStatusEnum.ENABLE.getStatus());
        // 拼接数据
        Map<Long, DeptDO> deptMap = deptService.getDeptMap(
                convertList(list, AdminUserDO::getDeptId));
        return success(UserConvert.convertSimpleList(list, deptMap));
    }


    @GetMapping("/simple-list2")
    @Operation(summary = "重写获取用户列表", description = "只包含被开启的用户，主要用于前端的下拉选项")
    public CommonResult<List<UserSimpleRespVO2>> getSimpleUserList2(UserRespVO respVO) {
        List<UserSimpleRespVO> list = userService.getUserListByStatus2(CommonStatusEnum.ENABLE.getStatus());
        for (UserSimpleRespVO item : list) {
            item.setPostIds2(convert(item.getPostIds()));
        }
        if (respVO.getPostId() != null) {
            // 使用并行流提升大集合处理速度
            list = list.parallelStream()
                    .filter(Objects::nonNull)
                    // 过滤空用户对象
                    .filter(user -> {
                        Set<Long> ids = user.getPostIds2();
                        return ids != null && ids.contains(respVO.getPostId());
                    })
                    .collect(Collectors.toList());
        }
        if (respVO.getNickname() != null) {
            list = list.parallelStream()
                    .filter(Objects::nonNull)
                    // 过滤空用户对象
                    .filter(user -> {
                        return user.getNickname().contains(respVO.getNickname());
                    })
                    .collect(Collectors.toList());
        }
        if (respVO.getDeptId() != null) {
            list = list.parallelStream()
                    .filter(Objects::nonNull)
                    // 过滤空用户对象
                    .filter(user -> {
                        return user.getDeptId().equals(respVO.getDeptId());
                    })
                    .collect(Collectors.toList());
        }
        // 拼接数据
        Map<Long, DeptDO> deptMap = deptService.getDeptMap(
                convertList(list, UserSimpleRespVO::getDeptId));
        List<UserSimpleRespVO2> userSimpleRespVO = UserConvert.convertSimpleList2(list, deptMap);
        for (UserSimpleRespVO2 item : userSimpleRespVO) {
            item.setLabel(item.getNickname());
            item.setValue(item.getId());
        }

        return success(userSimpleRespVO);
    }

    public static Set<Long> convert(String input) {
        Set<Long> result = new HashSet<>();
        // 1. 去除方括号
        String cleaned = input.replaceAll("[\\[\\]]", "");
        // 2. 分割元素（支持多元素，如 "[1, 2, 3]"）
        String[] elements = cleaned.split(",");
        // 3. 遍历转换
        for (String element : elements) {
            try {
                // 去除空白字符并转换为 Long
                Long num = Long.parseLong(element.trim());
                result.add(num);
            } catch (NumberFormatException e) {
                System.err.println("无效数字格式: " + element);
            }
        }

        return result;
    }

    @GetMapping("/get")
    @Operation(summary = "获得用户详情")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('system:user:query')")
    public CommonResult<UserRespVO> getUser(@RequestParam("id") Long id) {
        AdminUserDO user = userService.getUser(id);
        if (user == null) {
            return success(null);
        }
        // 拼接数据
        DeptDO dept = deptService.getDept(user.getDeptId());
        return success(UserConvert.convert(user, dept));
    }

    @GetMapping("/getUserDetailById")
    @Operation(summary = "获得当前用户详情(考勤等专用)")
    public CommonResult<UserSimpleRespVO2> getUserDetailById() {
        AdminUserDO user = userService.getUser(SecurityFrameworkUtils.getLoginUserId());
        if (user == null) {
            return success(null);
        }
        UserSimpleRespVO2 vo = BeanUtils.toBean(user, UserSimpleRespVO2.class);
        List<PostDO> postDOList = postService.getPostList(user.getPostIds());
        if (postDOList != null && !postDOList.isEmpty()) {
            vo.setPostName(postDOList.stream()
                    // 提取每个PostDO的name
                    .map(PostDO::getName)
                    // 过滤可能为null的name（可选，根据实际需求）
                    .filter(name -> name != null && !name.isEmpty())
                    // 用逗号连接所有name
                    .collect(Collectors.joining(",")));
        }

        return success(vo);
    }




    @GetMapping("/list-by-post-ids")
    @Operation(summary = "获得指定岗位的用户数组")
    @Parameter(name = "postIds", description = "岗位编号数组", example = "2,3", required = true)
    public CommonResult<List<AdminUserDO>> getUserListByPostIds(@RequestParam("postIds") Collection<Long> postIds){
        return success(userService.getUserListByPostIds(postIds));
    }


}
